<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>跨域的几种方案</title>
  </head>
  <body>
    <script>
      // fetch("http://localhost:9527/hero", { method: "GET" })
      //   .then((res) => {
      //     return res.json();
      //   })
      //   .then((res) => {
      //     console.log("=====", res);
      //   });

      // const jsonp = (url) => {
      //   window.callback = (resp) => {
      //     script.remove();
      //     console.log(resp);
      //   };
      //   var script = document.createElement("script");
      //   script.src = url;
      //   // 浏览器加载 script 脚步。获取到数据后会执行 window.callback 函数
      //   document.head.appendChild(script);
      // };

      // jsonp("http://localhost:9527/jsonp");

      const jsonp = (() => {
        let k = 1;
        function getCallBackName() {
          return `__jsonp_callback_${k++}`;
        }
        const jsonp = (url, cb) => {
          const cbName = getCallBackName();
          window[cbName] = (res) => {
            cb(res);
          };

          var script = document.createElement("script");
          script.src = url + "?callback=" + cbName;
          document.head.appendChild(script);
        };
        return jsonp;
      })();

      jsonp("http://localhost:9527/jsonp", (res) => {
        console.log("1===", res);
      });
      jsonp("http://localhost:9527/jsonp", (res) => {
        console.log("2===", res);
      });
    </script>
  </body>
</html>
